﻿using System;
using System.Collections.Generic;
using System.Drawing;

//子图形
namespace RoadSign.entity
{
    [Serializable()]
    class GraphicItem
    {
        public List<Point> points = new List<Point>();  //点集
        public Color color;

        public GraphicItem(Color color)
        {
            this.color = color;
        }

        //绘图
        public void paint(Graphics g)
        {
            if (points.Count > 1)
            {
                Pen p = new Pen(color);
                g.DrawLines(p, points.ToArray());   //绘制已经确定的折线
            }
        }

        //得到最后一个点
        public Point getLast()
        {
            return points[points.Count - 1];
        }

        //回退一笔
        public void removeLast()
        {
            if (points.Count > 0)
            {
                points.RemoveAt(points.Count - 1);
            }
        }

        //闭合
        public void close()
        {
            if (points.Count > 2)
            {
                points.Add(points[0]);
            }
        }

        //改变最后一条直线的长度和角度
        public void changeLine(int length, int agl)
        {
            double angle = agl * Math.PI / 180;
            if (points.Count - 2 >= 0)
            {
                Point last2 = points[points.Count - 2];
                Point p = new Point();

                p.X = (int)(last2.X + length * Math.Cos(angle));
                p.Y = (int)(last2.Y - length * Math.Sin(angle));

                this.points[points.Count - 1] = p;
            }
        }

        //显示当前直线的长度和角度
        public double[] showLine()
        {
            if (points.Count - 2 < 0)
                return null;
            return transform(points[points.Count - 2], points[points.Count - 1]);
        }

        //将两个点的坐标转换为极坐标形式（长度+角度）
        private double[] transform(Point p1, Point p2)
        {
            double[] result;
            result = new double[2];

            //长度（两点之间的距离）
            result[0] = Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));

            //角度(-180,180]（分类讨论）
            if (p2.X - p1.X > 0)    //(-90,90)
            {
                result[1] = -Math.Atan((p2.Y - p1.Y) * 1.0 / (p2.X - p1.X)) * 180 / Math.PI;
            }
            else if (p2.X - p1.X < 0)   //(90,180]U(-180,-90)
            {
                result[1] = ((p2.Y - p1.Y > 0 ? 1 : (-1)) * (-Math.PI) - Math.Atan((p2.Y - p1.Y) * 1.0 / (p2.X - p1.X))) * 180 / Math.PI;
            }
            else  //90,-90
            {
                result[1] = (p2.Y - p1.Y > 0 ? 1 : (-1)) * (-90);
            }

            //控制精度
            result[0] = Math.Round(result[0], 0);
            result[1] = Math.Round(result[1], 0);

            return result;
        }
    }
}
